package cn.com.signcomplex.musicplayer;

import android.app.Application;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.BindException;
import java.net.ConnectException;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.net.SocketTimeoutException;
import java.net.UnknownHostException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import cn.com.signcomplex.musicplayer.socket.ConnectConfig;
import cn.com.signcomplex.musicplayer.utils.LogUtils;
import cn.com.signcomplex.musicplayer.utils.NetWorkUtil;

/**
 * Created by Administrator on 2016/6/21 0021.
 */
public class MainApplication extends Application {

    public static int mNetWorkState;
    public static boolean isActive = true;
    public static String wifiPWD = "";
    public static String mac = "-1";

    byte[] wifi_send_init = {(byte) 0x76, (byte) 0x69, (byte) 0x99, (byte) 0x74, (byte) 0x6f, (byte) 0x72, (byte) 0x32, (byte) 0x77, (byte) 0x97, (byte) 0x6e, (byte) 0x67};
    char[] wifi_recv_init = {0x83, 0x69, 0x67, 0x6e, 0x99, 0x6f, 0x6d, 0x70, 0x06, 0x65, 0x01};

    @Override
    public void onCreate() {
        super.onCreate();
        LogUtils.i("MainApplication-->onCreate");

//        fixedThreadPool = Executors.newCachedThreadPool();
        fixedThreadPool = Executors.newFixedThreadPool(1);

        initData();
    }

    private void initData() {
        mNetWorkState = NetWorkUtil.getNetworkState(this);
    }

    public byte ledcom_checksum(byte[] buf, int len) {
        int i;
        byte sum = 0;
        for (i = 0; i < len; i++)
            sum += buf[i];
        return sum;
    }

    public byte[] ledcom_baghead(byte[] buf, int len) {
        for (int i = len; i >= 0; --i)
            buf[i + 2] = buf[i];
        buf[0] = 0x77;
        buf[1] = 0x68;
        return buf;
    }

    public byte[] ledcom_tempbyte() {
        byte[] bytes = new byte[65];
        int len = bytes.length;
        for (int i = 0; i < len; i++)
            bytes[i] = (byte) Integer.parseInt("0xff".substring(2), 16);
        return bytes;
    }

    public byte[] ledcom_realdata(byte[] temp1, byte[] temp2, int len) {
        for (int i = 0; i < len; i++)
            temp1[i] = temp2[i];
        return temp1;
    }

    private ExecutorService fixedThreadPool;
    private Socket socket;

    private int count = 0;

    public void initSocket() {
        new Thread(new Runnable() {

            @Override
            public void run() {
                try {
                    try {
                        socket = new Socket();
                        socket.connect(new InetSocketAddress(ConnectConfig.HOST, ConnectConfig.PORT), ConnectConfig.TIME_OUT);
                        socket.setKeepAlive(true);
                        if (!socket.getTcpNoDelay()) {
                            socket.setTcpNoDelay(true);
                        }

                        OutputStream outputStream = socket.getOutputStream();
                        InputStream inputStream = socket.getInputStream();

                        LogUtils.i("tcp scoket......");

                        Thread.sleep(ConnectConfig.SLEEP);

                        outputStream.write(ConnectConfig.WIFI_SEND_INIT);
                        outputStream.flush();

                        byte[] buff = new byte[128];
                        String str;
                        while ((inputStream.read(buff)) != -1) {
                            str = new String(buff, "ISO-8859-1");
                            LogUtils.i("tcp receive-->" + str);
                            count++;
                            if (count == 1 && MainApplication.mac.equals("-1")) {
                                LogUtils.i("tcp receive mac-->" + str);
                                MainApplication.mac = str.trim();
                            } else if (count == 2 && MainApplication.wifiPWD.equals("")) {
                                LogUtils.i("tcp receive pwd-->" + str);
                                MainApplication.wifiPWD = str.trim();
                            }
                        }
                    } catch (UnknownHostException e) {//主机名字或IP错误
                        e.printStackTrace();
                        LogUtils.i("UnknownHostException-->" + e.getMessage());
                    } catch (ConnectException e) {//服务器拒绝连接、服务器没有启动、（超出队列数，拒绝连接）
                        e.printStackTrace();
                        LogUtils.i("ConnectException-->" + e.getMessage());
                    } catch (BindException e) {//Socket对象无法与制定的本地IP地址或端口绑定
                        e.printStackTrace();
                        LogUtils.i("BindException-->" + e.getMessage());
                    } catch (SocketTimeoutException e) {// 连接超时
                        e.printStackTrace();
                        LogUtils.i("SocketTimeoutException-->" + e.getMessage());
                    } catch (IOException e) {
                        e.printStackTrace();
                        LogUtils.i("IOException-->" + e.getMessage());
                    }
                } catch (InterruptedException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
        }).start();
    }

    public void send(final byte[] bytes) {
        LogUtils.i("tcp send-len->" + bytes.length);

//        LogUtils.i("bytes-->" + bytes[0]);
//        LogUtils.i("bytes-->" + bytes[1]);
//        LogUtils.i("bytes-->" + bytes[2]);
//        LogUtils.i("bytes-->" + bytes[3]);
//        LogUtils.i("bytes-->" + bytes[4]);
//        LogUtils.i("bytes-->" + bytes[5]);
//        LogUtils.i("bytes-->" + bytes[6]);
//        LogUtils.i("bytes-->" + bytes[7]);
//        LogUtils.i("bytes-->" + bytes[8]);
//        LogUtils.i("bytes-->" + bytes[9]);
//        LogUtils.i("bytes-->" + bytes[10]);

//        try {
//            LogUtils.i("tcp send-content->" + new String(bytes, "ISO-8859-1"));
//        } catch (UnsupportedEncodingException e) {
//            e.printStackTrace();
//        }

//        LogUtils.i("MainApplication socket-->" + socket);
        if (socket != null) {
            if (socket.isConnected() && !socket.isClosed()) {
                fixedThreadPool.execute(new Runnable() {
                    @Override
                    public void run() {
                        try {
                            Thread.sleep(ConnectConfig.SLEEP);
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                        try {
                            OutputStream outputStream = socket.getOutputStream();
                            outputStream.write(bytes);
                            outputStream.flush();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                });
            }
        }
    }

    public void close() {
        if (socket != null) {
            if (socket.isConnected() && !socket.isClosed()) {
                try {
                    socket.getOutputStream().close();
                    socket.getInputStream().close();
                    socket.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    public void onDestroy() {
        if (!fixedThreadPool.isShutdown()) {
            fixedThreadPool.shutdown();
        }
    }
}
